<template>
  <a-page-header>
    <a-card>
      <a-table :columns="columns" :data-source="data"
               :loading="loading" :defaultExpandedRowKeys="[1]"
               :rowKey="record => record.areaId" >
        <template slot="title">
          <a-row type="flex" justify="space-between">
            <a-col :span="4">
              <a-button type="primary" style="margin-left: 10px;" icon="plus-circle" @click="showAddModal()" >
                新增地域
              </a-button>
              <a-modal
                  :title="modalForm.title"
                  :visible="modalForm.visible"
                  :confirm-loading="modalForm.confirmLoading"
                  okText="提交"
                  cancelText="取消"
                  @ok="handleModalOk"
                  @cancel="handleModalCancel">
                <a-form-model @submit="handleModalFormSubmit"
                              :label-col="{span:4}" :wrapper-col="{span:14}" ref="addForm"
                              :model="addForm" :rules="modalForm.modalFormRules"  >
                  <a-form-model-item label="上级地域" ref="areaPid" prop="areaPid">
                    <a-tree-select
                        v-model="addForm.areaPid"
                        :disabled="modalForm.isDisabled"
                        style="width: 100%"
                        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                        :tree-data="data"
                        placeholder="请选择父节点"
                        :replaceFields="modalForm.selectTreeReplaceFields"
                    >
                    </a-tree-select>
                  </a-form-model-item>

                  <a-form-model-item label="地域名称" ref="areaName" prop="areaName">
                    <a-input v-model="addForm.areaName" placeholder="地域名称"/>
                  </a-form-model-item>

                  <a-form-model-item label="地域排序" ref="sort" prop="sort">
                    <a-input-number v-model="addForm.sort" :min="1" :max="50" placeholder="地域排序" />
                  </a-form-model-item>

                  <a-form-model-item label="是否启用" ref="status" prop="status">
                    <a-radio-group v-model="addForm.status">
                      <a-radio-button value="1">
                        启用
                      </a-radio-button>
                      <a-radio-button value="0">
                        禁用
                      </a-radio-button>
                    </a-radio-group>
                  </a-form-model-item>
                </a-form-model>

              </a-modal>
            </a-col>

            <a-col >
              <a-form-model ref="queryForm"
                            layout="inline" :model="formInline">
                <a-form-model-item ref="areaNameLike" prop="areaNameLike">
                  <a-input v-model="formInline.areaNameLike" placeholder="模糊查询地域名称">
                  </a-input>
                </a-form-model-item>

                <a-form-model-item ref="searchStatus" prop="searchStatus">
                  <a-select v-model="formInline.searchStatus" style="width: 200px" placeholder="请选择要查询的地域状态">
                    <a-select-option value="1">
                      启用
                    </a-select-option>
                    <a-select-option value="0">
                      禁用
                    </a-select-option>
                  </a-select>
                </a-form-model-item>

                <a-form-model-item>
                  <a-button
                      type="primary"
                      @click="handleSubmit"
                      :disabled="isDisable">
                    查询
                  </a-button>
                  <a-button style="margin-left: 10px;" @click="resetSearchForm('queryForm')">
                    重置
                  </a-button>
                </a-form-model-item>
              </a-form-model>
            </a-col>
          </a-row>
        </template>

        <template #status="status">
          <a-tag :color="status?'green':'volcano'">
            <span v-if="status">启用</span>
            <span v-else>禁用</span>
          </a-tag>
        </template>

        <template #action="record">
          <a-button type="primary" shape="circle" icon="edit" @click="showEditModal(record)" />
          <a-divider type="vertical" />
          <a-popconfirm
              :title="`确认要删除:${record.areaName}吗?`"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleDeleteArea(record.areaId)"
          >
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a-button type="danger" shape="circle" icon="delete" />
          </a-popconfirm>

        </template>

      </a-table>
    </a-card>
  </a-page-header>
</template>

<script>
import {addArea,updateArea,deleteAreaById,getAreaTree} from "@/api/area";

const columns = [
  {
    title: '地域标识',
    dataIndex: 'areaId',
    key: 'areaId',
  },
  {
    title: '地域名称',
    dataIndex: 'areaName',
    key: 'areaName',
  },
  {
    title: '排序',
    dataIndex: 'sort',
    key: 'sort',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  }
];

const selectTreeReplaceFields = {
  children:'children',
  title:'areaName',
  key:'areaId',
  value: 'areaId'
}

const modalFormRules = {
  areaPid: [
    {required: true, message: '请选择上级地域',trigger:['blur','change']},
  ],
  areaName: [
    {required: true, message: '请输入地域名称', trigger: ['blur']},
  ],
  sort: [
    {required: true, message: '请输入当前地域在同级地域内的排序序号', trigger: 'blur'},
  ],
  status:[
    {required: true, message: '请选择是否启用', trigger: 'change'}
  ]
}
export default {
  name: "SystemArea",
  data() {
    return {
      formInline: {
        areaNameLike: '',
        searchStatus: undefined,
      },
      modalForm:{
        title:'',
        visible:false,
        confirmLoading: false,
        selectTreeReplaceFields,
        modalFormRules,
        isDisabled:false
      },
      addForm:{
        areaId:undefined,
        areaPid:undefined,
        areaName:'',
        status:undefined,
        sort:undefined
      },
      data:[],
      loading:false,
      columns,
      isHandleSubmit:false,
    }
  },
  mounted() {
    this.getAreaTreeData()
  },
  methods:{
    // 查询表单提交
    print(a,b){
      console.log(a,b)
    },
    handleSubmit() {
      console.log(this.formInline)
      this.isHandleSubmit = true;
      let submitParams = {
        rootAreaId:1
      }

      if (this.formInline.menuNameLike!==''){
        submitParams['areaNameLike'] = this.formInline.areaNameLike
      }
      if (typeof (this.formInline.searchStatus)!=='undefined'){
        submitParams['areaStatus']=this.formInline.searchStatus==='1'
      }
      console.log('SystemArea handleSubmit',submitParams)
      this.getAreaTreeData(submitParams)
    },
    resetSearchForm(formName) {
      this.$refs[formName].resetFields();
      if (this.isHandleSubmit){
        this.getAreaTreeData()
      }
    },
    // 获取树形API数据
    getAreaTreeData(param= {rootAreaId:1}){
      this.loading = true
      getAreaTree(param).then(res=>{
        this.data = res.data
      }).catch(err=>{
        console.log("SystemArea:getAreaTreeData:"+err.message);
      }).finally(()=>{
        this.loading = false
      })
    },
    // addForm start
    showAddModal(){
      this.modalForm.isDisabled = false;
      this.modalForm.visible =  true
      this.modalForm.title = '新增地域'
    },
    showEditModal(record){
      console.log(record)
      this.modalForm.isDisabled = true
      this.modalForm.visible =  true
      this.modalForm.title = '修改地域'
      let {areaId, areaPid, areaName, status,sort} = record
      this.addForm = {
        areaId, areaPid, areaName,sort,
        status: status?"1":"0"
      }
    },
    // 处理modal里的表单提交
    handleModalOk(){
      this.handleModalFormSubmit()
    },
    handleModalCancel(){
      this.modalForm.visible = false
      this.resetForm('addForm')
    },
    handleModalFormSubmit(){
      this.$refs['addForm'].validate(valid=>{
        if (valid) {
          let submitData = this.addForm
          submitData.status = this.addForm.status === "1"
          this.modalForm.confirmLoading = true
          if (this.modalForm.isDisabled){
            this.handleUpdateArea(submitData)
          }else {
            this.handleAddArea(submitData)
          }
        } else {
          this.handleFiled(new Error('表单校验不通过'))
          return false;
        }
      })
    },
    resetForm(formName) {
      this.addForm = {
        areaId:undefined,
        areaPid:undefined,
        areaName:'',
        status:undefined,
        sort:undefined
      }
      this.$refs[formName].resetFields();
    },
    // addForm end
    handleAddArea(area){
      addArea(area).then(res=>{
        this.handleSuccess(res)
        this.resetForm('addForm')
      }).catch(err=> this.handleFiled(err))
    },
    handleDeleteArea(areaId){
      deleteAreaById(areaId).then(res=>{
        this.handleSuccess(res)
      }).catch(err=> this.handleFiled(err))
    },
    handleUpdateArea(area){
      updateArea(area).then(res=>{
        this.handleSuccess(res)
        this.resetForm('addForm')
      }).catch(err=> this.handleFiled(err))
    },
    handleSuccess(res){
      this.modalForm.confirmLoading = false
      this.$notification['success']({
        message: '成功',
        description: `${res.data}`,
        duration: 4
      })
      this.getAreaTreeData()
    },
    handleFiled(err){
      this.modalForm.confirmLoading = false
      console.log(err.message)
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).message || {}).message||err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  },

  computed:{
    isDisable(){
      return this.formInline.areaNameLike===''&&!this.formInline.searchStatus;
    }
  }
}
</script>

<style scoped>

</style>
